#!/bin/bash

#This script is part of svn-scripts. It is licensed under the GNU GENERAL PUBLIC LICENSE Version 2.
#Check the LICENSE.TXT file included with svn-scripts or check http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt for details.

#Original version: http://mail-archives.apache.org/mod_mbox/db-derby-dev/200808.mbox/%3Cb93df62d0808131732r2c10f271v6d691e4a173fc1c8@mail.gmail.com%3E

#Applies a diff file to the current repository and adds all new unversioned files to it. Works both with p0 and p1 diff files.
if test -z "$1"
then
	echo "Syntax: svnpatch <patch file>";
	exit;
fi

#Apply the patch and store the verbose output.
patch -p0 --verbose -i $1 &> /tmp/svnpatchout1

#Check for incorrect parameters (folder).
result=`cat /tmp/svnpatchout1 | grep "directory"`;

if [ -n "$result" ]; then
	echo "Error: $1 is not a file.";
	exit;
fi

#Check for incorrect parameters (file).
result=`cat /tmp/svnpatchout1 | grep "garbage"`;

if [ -n "$result" ]; then
	echo "Error: $1 is not a valid diff / patch file.";
	exit;
fi

echo "Applying patch $1";

#Check for -p0 errors.
result=`cat /tmp/svnpatchout1 | grep "wrong -p"`;
type="p0";
if [ -n "$result" ]; then
	echo "Patch using p1 detected.";
	patch -R -p0 -i $1 &> /dev/null
	patch -p1 --verbose -i $1 &> /tmp/svnpatchout1
	type='p1';
fi

#Show rejects.
cat /tmp/svnpatchout1 | grep -i "rejects"

#Get the files changed by the diff file.
cat /tmp/svnpatchout1 | grep "|+++" | sed -e "s/|+++ //g" | sed -e "s/(revision 0)//g" | sed "s/(working copy)//g" > /tmp/svnpatchout2

if [ "$type" == "p1" ]; then
	#Strip first leading component.
	cat /tmp/svnpatchout2 | sed -e "s/[^\/]*\///p" > /tmp/svnpatchout1
	cp /tmp/svnpatchout1 /tmp/svnpatchout2
fi

svn status | sed "/^[^?]/d" | awk '{print $2}' > /tmp/svnpatchout1

#Run svn add for each file.
for i in $(cat /tmp/svnpatchout1);
	do
	result=`cat /tmp/svnpatchout2 | grep "$i"`;
	if [ "$result" != "" ]; then
		svn add $i
	fi
done

#Clean up.
rm /tmp/svnpatchout*
